<?php

use models\dao\NivelDAO;
use models\Usuario;
use Doctrine\Common\Collections\ArrayCollection;
use models\dao\UsuarioDAO;


Class Usuarios extends CI_Controller {

	private $userDAO;
	private $nivelDAO;
	private $em;

	public function __construct() {
		parent::__construct();

		$this->em = $this->doctrine->em;
		$this->userDAO = new UsuarioDAO($this->em);
		$this->nivelDAO = new NivelDAO($this->em);

		$this->load->helper('url');
	}

	public function findAll() {
		$allUsers = $this->userDAO->findAll();

		$result['result'] = array();

		foreach ($allUsers as $user) {
			array_push($result['result'], $user->toArray());
		}
		echo json_encode($result);
	}

	public function save() {
		$data = (array) json_decode($_POST['data']);

		if (empty($data['id'])) {
			$user = new models\Usuario();
		} else {
			$user = $this->userDAO->findByPrimaryKey($data['id']);
		}

		$user->setNome($data['nome']);
		$user->setEmail($data['email']);
		$user->setSenha($data['senha']);
		$user->setNivel($this->nivelDAO->findByPrimaryKey($data['nivelId']));

		$this->userDAO->save($user);

		$this->em->close();

		$result['data']['success'] = true;
		echo json_encode($result);
	}

	public function delete() {
		$data = (array) json_decode($_POST['data']);
		$result['data']['success'] = true;
		try {
			$user = $this->userDAO->findByPrimaryKey($data['id']);
			$this->userDAO->delete($user);
			echo json_encode($result);
		} catch (Exception $e) {
			$this->em->close();
			$result['data']['success'] = false;
			$result['data']['message'] = $e->getMessage();
			echo json_encode($result);
		}
	}

	public function login() {
		$email = $_POST['usuario'];
		$senha = $_POST['senha'];

		$user = $this->userDAO->login($email, $senha);

		if (!empty($user)) {
			$data =  $user[0]->toArray();
			$result['success'] = TRUE;
			$result['user'] = $data;
			$this->session->set_userdata('user', $data);
		} else {
			$result['success'] = FALSE;
		}

		echo json_encode($result);
	}

	public function isLogged() {
		$user = $this->session->userdata('user');
		if ($user) {
			echo json_encode($user);
		} else {
			echo "";
		}
	}

	public function logout() {
		$this->session->unset_userdata('user');
		redirect('/home');
	}

	public function test() {
		$user = $this->session->userdata('user');
		print_r($user);
	}
}